package com.example.locationgps;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.icu.text.SimpleDateFormat;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.BlockingDeque;

@RequiresApi(api = Build.VERSION_CODES.N)
public class MainActivity extends AppCompatActivity {

    //定义文本和按钮
    private Button btn;
    private EditText editText;
    private Button stopbtn;
    private TextView time;
    private TextView lon;
    private TextView lat;
    private TextView hei;
    private TextView acc;
    private TextView sp;
    private TextView bea;
    private TextView pro;
    private RadioButton mRadioButton1;
    private RadioButton mRadioButton2;

    // 定义LocationManager对象
    private LocationManager locationManager; 

    //定义GPS信息数组
    List<GPSInfor> gpslist = new ArrayList<>();
    List<GPSInfor> gpslist2 = new ArrayList<>();
    //声明GPS信息类
    GPSInfor gpsInfor = new GPSInfor();

    private static Context context;
    //获取当前时间
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
    private String name;//定义文件名

    String sxtid = null;

    int equitype = 0;

    boolean bl = true;

    Long pltime = 0L;
    //声明保存数据库
    LoginActivity loginActivity = new LoginActivity();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = getApplicationContext();
        initData();
    }

    private void initData() {
        btn = (Button) findViewById(R.id.btn);
        editText = findViewById(R.id.phonenumber);
        stopbtn = findViewById(R.id.stopbtn);
        time = findViewById(R.id.time);
        lon = findViewById(R.id.lon);
        lat = findViewById(R.id.lat);
        hei = findViewById(R.id.hei);
        acc = findViewById(R.id.acc);
        sp = findViewById(R.id.sp);
        bea = findViewById(R.id.bea);
        pro = findViewById(R.id.pro);
        mRadioButton1 = findViewById(R.id.radioButton1);
        mRadioButton2 = findViewById(R.id.radioButton2);

        //gps选择情况
        mRadioButton1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.radioButton1:
                        //true 为选中false没有选中
                        mRadioButton2.setChecked(false);
                        mRadioButton1.setChecked(true);
                        equitype = 2;
                        break;
                }
            }
        });
        mRadioButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.radioButton2:
                        mRadioButton2.setChecked(true);
                        mRadioButton1.setChecked(false);
                        equitype = 1;
                        break;

                }
            }
        });

        //开始记录gps数据
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (equitype == 0) {  //用户必须先选择gps设备
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setMessage("请选择gps设备！！！");
                    builder.show();
                } else if (editText.getText().toString().equals("") || editText.getText().toString().equals(null)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setMessage("请输入视频片段标识！！！");
                    builder.show();
                } else {
                    btn.setEnabled(false);
                    stopbtn.setEnabled(true);
                    Date date = new Date(System.currentTimeMillis());
                    //生成记录文件的名称
                    name = simpleDateFormat.format(date);
                    //视频记录批次id
                    sxtid = editText.getText().toString();
                    //启动gps
                    if (bl == true) {
                        System.out.println("启动GPS定位");
                        bl = true;
                        getLocation();
                    } else {
                        System.out.println("再次启动");
                        bl = true;
                    }

                    //启动次线程将数据存入数据库
                    new Thread(new thread()).start();
                }
            }
        });

        //结束数据获取
        stopbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn.setEnabled(true);
                stopbtn.setEnabled(false);
                bl = false;
                time.setText("暂无数据");
                lon.setText("暂无数据");
                lat.setText("暂无数据");
                hei.setText("暂无数据");
                acc.setText("暂无数据");
                sp.setText("暂无数据");
                bea.setText("暂无数据");
                pro.setText("暂无数据");
            }
        });
    }

    private synchronized void AddGpsPoint(GPSInfor infor) {
        gpslist.add(infor);
    }

    private synchronized void CopyGpsList(Connection connection ) {
        if(gpslist.size() != 0){
            for (int i = gpslist.size()-1;i>=0;i--){
                GPSInfor infor = gpslist.remove(0);
                loginActivity.dataToDB(connection, infor);
            }
        }
//        if (gpslist2.size() == 0) {
//            gpslist2.addAll(gpslist);
//            gpslist.clear();
//            return true;
//        }
//        return false;
    }

    //将数据存入数据库
    public class thread implements Runnable {
        @Override
        public void run() {
            Connection connection = loginActivity.conectDB();
            if (connection == null) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("数据库连接失败");
                builder.show();
            } else {
                while (true) {
                    try {
                        CopyGpsList(connection);
//                        for (int i = gpslist2.size() - 1; i >= 0; i--) {
//                            GPSInfor infor = gpslist2.remove(0);
//                            System.out.println(infor.toString());
//                            loginActivity.dataToDB(connection, infor);
//                        }
//                        Thread.sleep(3000);
                        if (bl == false) break;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    System.out.println("数据库连接关闭");
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                gpslist.clear();
                gpslist2.clear();
                System.out.println("线程关闭成功");
            }
        }
    }

    /* 获取定位方法 */
    public void getLocation() {
        //1.获取系统LocationManager服务
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);//低精度，中精度高精度获取不到location。
        criteria.setAltitudeRequired(false);//不要求海拔
        criteria.setBearingRequired(false);//不要求方位
        criteria.setCostAllowed(true);//允许有花费
        criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗

        String locationProvider = locationManager.getBestProvider(criteria, true);
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setMessage("没有权限！！");
            builder.show();
            return;
        }
        //2.获取GPS最近的定位信息
        Location location = locationManager.getLastKnownLocation(locationProvider);

        //3.将location里面的位置信息展示在edittext中
//        updateLocation(location);


        //4.设置没一秒获取一次GPS的定位信息
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {

            @Override
            public void onLocationChanged(@NonNull Location location) {
                //当GPS定位信息发生改变时，更新位置
                updateLocation(location);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(@NonNull String provider) {
                //当GPS LocationProvider可用时，更新位置
                System.out.println("位置提供者:" + location.getProvider());
                updateLocation(location);

            }

            @Override
            public void onProviderDisabled(@NonNull String provider) {

            }
        });
    }


    private void updateLocation(Location location) {
        if (location != null && bl) {
            Date ddate = new Date(System.currentTimeMillis());
            Long alineTime = ddate.getTime();
            String datae = simpleDateFormat.format(ddate);

            Long ltime = location.getTime();
            String realtime = simpleDateFormat.format(ltime);

            time.setText(realtime);
            lon.setText(String.valueOf(location.getLongitude()));
            lat.setText(String.valueOf(location.getLatitude()));
            hei.setText(String.valueOf(location.getAltitude()));
            acc.setText(String.valueOf(location.getAccuracy()));
            sp.setText(String.valueOf(location.getSpeed()));
            bea.setText(String.valueOf(location.getBearing()));
            pro.setText(location.getProvider());
            System.out.println(datae);

            double lon = location.getLongitude();   // 径度
            double lat = location.getLatitude();    // 纬度
            double mlon = lon * 20037508.34 / 180;    //经度转墨卡托
            double mlat = (Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180)) * 20037508.34 / 180;   //纬度转墨卡托
            double hei = location.getAltitude();    //高度
            double acc = location.getAccuracy();    //精度
            double sp = location.getSpeed();
            double bea = location.getBearing();
            String pro = location.getProvider();

            if(!pltime.equals(alineTime)){
                String own = UUID.randomUUID().toString();
                pltime = alineTime;
                gpsInfor.setId(own);
                gpsInfor.setRealtime(realtime);
                gpsInfor.setLon(lon);
                gpsInfor.setLat(lat);
                gpsInfor.setMlon(mlon);
                gpsInfor.setMlat(mlat);
                gpsInfor.setLtime(ltime);
                gpsInfor.setSxtid(sxtid);
                gpsInfor.setSysdate(datae);
                gpsInfor.setEquitype(equitype);
                gpsInfor.setAlinetime(alineTime);
                gpsInfor.setDirection(bea);
                gpsInfor.setSpeed(sp);

                AddGpsPoint(gpsInfor);
                String log = realtime + "," + lon + "," + lat + "," + mlon + "," + mlat + "," + hei + "," + acc + "," + sxtid + "," + datae + "," + sp + "," + bea + "," + pro + "," + "\n";
                DLog.writeFileSdcard(context, name + ".txt", log);
            }

        } else {
            time.setText("暂无数据");
            lon.setText("暂无数据");
            lat.setText("暂无数据");
            hei.setText("暂无数据");
            acc.setText("暂无数据");
            sp.setText("暂无数据");
            bea.setText("暂无数据");
            pro.setText("暂无数据");
        }
    }

    public static byte[] byteMerger(byte[] bt1, byte[] bt2) {
        byte[] bt3 = new byte[bt1.length + bt2.length];
        System.arraycopy(bt1, 0, bt3, 0, bt1.length);
        System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
        return bt3;
    }

}